<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class SpecificationTemplate extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'slug',
        'description',
        'category_id',
        'attributes_config',
        'display_config',
        'is_active',
        'is_default',
        'sort_order',
        'meta_data',
    ];

    protected $casts = [
        'attributes_config' => 'array',
        'display_config' => 'array',
        'is_active' => 'boolean',
        'is_default' => 'boolean',
        'sort_order' => 'integer',
        'meta_data' => 'array',
    ];

    /**
     * 关联分类
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    /**
     * 作用域：按分类筛选
     */
    public function scopeForCategory($query, $categoryId)
    {
        return $query->where(function ($q) use ($categoryId) {
            $q->where('category_id', $categoryId)
              ->orWhere('category_id', null); // 全局模板
        });
    }

    /**
     * 作用域：启用的模板
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * 作用域：默认模板
     */
    public function scopeDefault($query)
    {
        return $query->where('is_default', true);
    }

    /**
     * 作用域：按排序
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order', 'desc')->orderBy('created_at', 'desc');
    }

    /**
     * 获取模板的规格属性列表
     */
    public function getAttributeList(): array
    {
        return $this->attributes_config ?? [];
    }

    /**
     * 检查是否包含特定属性
     */
    public function hasAttribute(string $attributeSlug): bool
    {
        $attributes = $this->getAttributeList();
        return collect($attributes)->contains('slug', $attributeSlug);
    }

    /**
     * 获取特定属性的配置
     */
    public function getAttributeConfig(string $attributeSlug): ?array
    {
        $attributes = $this->getAttributeList();
        return collect($attributes)->firstWhere('slug', $attributeSlug);
    }
}